package cn.edu.sxw.web.server.service;

import cn.edu.sxw.web.server.bean.ValidateCode;

import java.util.HashMap;
import java.util.Random;
import java.util.UUID;

public class ValidateCodeService {
    public static HashMap<String, String> ValidateCodeStore = new HashMap<>();

    //产生一个验证码
    public ValidateCode createValidate() {
        //随机码
        String randomCode = UUID.randomUUID().toString();
        //2个随机数
        Random random = new Random();
        Integer number1 = random.nextInt(20);
        Integer number2 = random.nextInt(20);

        Integer randomOp=random.nextInt(3);
        //算式               //答案
        String imageText="",result ="";
        switch (randomOp){
            case 0:{//加法
                imageText = number1 + "+" + number2 + "=?";
                result=String.valueOf(number1 + number2);
                break;
            }
            case 1:{//减法
                if(number1>=number2){//避免负数，大数字在前
                    imageText = number1 + "-" + number2 + "=?";
                    result=String.valueOf(number1 - number2);
                }else{
                    imageText = number2 + "-" + number1 + "=?";
                    result=String.valueOf(number2 - number1);
                }
                break;
            }
            case 2:{//乘法
                imageText = number1 + "*" + number2 + "=?";
                result=String.valueOf(number1 * number2);
                break;
            }
        }

        //存储到Store中,随机码作为键，算是和答案作为值，用逗号隔开
        ValidateCodeStore.put(randomCode, imageText + "," + result);

        ValidateCode validateCode = new ValidateCode(randomCode);
        return validateCode;
    }

    //校验验证码是否正确
    public boolean validate(String randomCode, String validateCode) {
        if (ValidateCodeStore.containsKey(randomCode)) {
            String validateString = ValidateCodeStore.get(randomCode);
            String answer = validateString.split(",")[1];

            //校验一次，无论对错立即失效
            ValidateCodeStore.remove(randomCode);
            return answer.equals(validateCode);
        }
        return false;
    }

    //根据随机码获取验证码算式文本
    public String getValidateText(String randomCode) {
        if (ValidateCodeStore.containsKey(randomCode)) {
            String validateString = ValidateCodeStore.get(randomCode);
            return validateString.split(",")[0];
        }
        return null;
    }
}
